using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Collections.Generic;
using System.Text;

using Ample.Model;
using Ample.BLL.Store;
using Ample;

public partial class ShoppingCart : BasePage
{
    //private bool _shipping = false;
    //private bool _holdForPickup = false;

    protected void Page_Load(object sender, EventArgs e)
    {         
        UpdateTotals();
    }

    protected void UpdateTotals()
    {         
        // update the quantities
        //foreach (GridViewRow row in gvwOrderItems.Rows)
        //{
        //    TableCell tc = gvwOrderItems.Rows[row.RowIndex].Cells[0];
        //    DropDownList ddl = (DropDownList)tc.FindControl("ddlHandling");
        //    string slctHandlingOpt = ddl.SelectedValue.ToString();

        //    switch (slctHandlingOpt)
        //    {
        //        case "0": if (!_holdForPickup) _holdForPickup = true;
        //            break;
        //        case "1": if(!_shipping) _shipping = true;
        //            break;
        //    }
 
        //}

        // display the subtotal and the total amounts
        lblSubTotal.Text = this.FormatPrice(this.Profile.ShoppingCart.Total);
        //lblShippingCost.Text = _holdForPickup?this.FormatPrice(20.0m): this.FormatPrice(0.0m);
        lblGST.Text = this.FormatPrice(0.0m);
        lblPST.Text = this.FormatPrice(0.0m);  
        lblTotal.Text = this.FormatPrice(this.Profile.ShoppingCart.Total);

        // if the shopping cart is empty, hide the link to proceed
        if (this.Profile.ShoppingCart.Items.Count == 0)
        {
            panTotals.Visible = false;
        }

        gvwOrderItems.DataBind();
    }

    protected void gvwOrderItems_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {
        UpdateTotals();
    }

    protected void btnUpdateTotals_Click(object sender, EventArgs e)
    {
        UpdateTotals();
    }

    protected void gvwOrderItems_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton btn = e.Row.Cells[3].Controls[0] as LinkButton;
            btn.OnClientClick = "if (confirm('Are you sure you want to remove this product from the shopping cart?') == false) return false;";
        }
    }

    protected void wizSubmitOrder_ActiveStepChanged(object sender, EventArgs e)
    {
     //if (wizSubmitOrder.ActiveStepIndex == 1)
     //{
     //   UpdateTotals();

     //   if (this.User.Identity.IsAuthenticated)
     //   {
     //      if (ddlCountries.Items.Count == 1)
     //      {
     //         ddlCountries.DataSource = Helpers.GetCountries();
     //         ddlCountries.DataBind();
     //      }

     //      if (txtFirstName.Text.Trim().Length == 0)
     //         txtFirstName.Text = this.Profile.FirstName;
     //      if (txtLastName.Text.Trim().Length == 0)
     //         txtLastName.Text = this.Profile.LastName;
     //      if (txtEmail.Text.Trim().Length == 0)
     //         txtEmail.Text = Membership.GetUser().Email;
     //      if (txtStreet.Text.Trim().Length == 0)
     //         txtStreet.Text = this.Profile.Address.Street;
     //      if (txtPostalCode.Text.Trim().Length == 0)
     //         txtPostalCode.Text = this.Profile.Address.PostalCode;
     //      if (txtCity.Text.Trim().Length == 0)
     //         txtCity.Text = this.Profile.Address.City;
     //      if (txtState.Text.Trim().Length == 0)
     //         txtState.Text = this.Profile.Address.State;
     //      if (ddlCountries.SelectedIndex == 0)
     //         ddlCountries.SelectedValue = this.Profile.Address.Country;
     //      if (txtPhone.Text.Trim().Length == 0)
     //         txtPhone.Text = this.Profile.Contacts.Phone;
     //      if (txtFax.Text.Trim().Length == 0)
     //         txtFax.Text = this.Profile.Contacts.Fax;
     //   }
     //}
     //else if (wizSubmitOrder.ActiveStepIndex == 2)
     //{
     //   lblReviewFirstName.Text = txtFirstName.Text;
     //   lblReviewLastName.Text = txtLastName.Text;
     //   lblReviewStreet.Text = txtStreet.Text;
     //   lblReviewCity.Text = txtCity.Text;
     //   lblReviewState.Text = txtState.Text;
     //   lblReviewPostalCode.Text = txtPostalCode.Text;
     //   lblReviewCountry.Text = ddlCountries.SelectedValue;

     //   lblReviewSubtotal.Text = this.FormatPrice(this.Profile.ShoppingCart.Total);
     //   lblReviewShippingMethod.Text = ddlShippingMethods.SelectedItem.Text;
     //   lblReviewTotal.Text = this.FormatPrice(this.Profile.ShoppingCart.Total + 
     //      Convert.ToDecimal(ddlShippingMethods.SelectedValue));
     //}
    }
    protected void lBtnSubOrder_Click(object sender, EventArgs e)
    {
        // check that the user is still logged in (the cookie may have expired)
        // and if not redirect to the login page
        if (this.User.Identity.IsAuthenticated)
        {
            //saves the order into the DB, and clear the shopping cart in the profile
            MembershipUser mu = Membership.GetUser();

            System.Data.Linq.EntitySet<OrderItem> loi = new System.Data.Linq.EntitySet<OrderItem>();
            int line = 0;
            foreach(ShoppingCartItem sci in this.Profile.ShoppingCart.Items)
                loi.Add(new OrderItem{ ProductId = sci.ID, Title = sci.Title, UnitPrice = sci.UnitPrice, Line = ++line, Package = sci.Package, Description = sci.Description}); 
            
            Order order = new Order{ UserId = (Guid)mu.ProviderUserKey, AddedDate = DateTime.Now  , SubTotal = this.Profile.ShoppingCart.Total, OrderItems = loi};
            OrderStatus os = new OrderStatus{ AddedBy = "Self", AddedDate = DateTime.Now, Status = Ample.DAL.Store.PaymentStatus.Pending.ToString()};
            order.OrderStatuses.Add(os);
            
            OrderBO obo = new OrderBO();
            int orderID = obo.InsertOrder(order);

            this.Profile.ShoppingCart.Clear();

            Order orderDB = obo.GetOrderById(orderID);

            //redirect to PayPal for the credit-card payment
            this.Response.Redirect(GetPayPalPaymentUrl(orderDB), false);
        }
        else
            this.RequestLogin();
    }

    private string GetPayPalPaymentUrl(Order order)
    {
        string serverUrl = (Globals.Settings.Store.SandboxMode ?
           "https://www.sandbox.paypal.com/us/cgi-bin/webscr" :
           "https://www.paypal.com/us/cgi-bin/webscr");
        string amount = order.SubTotal.ToString("N2").Replace(',', '.');
        //string shipping = order.Shipping.ToString("N2").Replace(',', '.');

        string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(
           HttpContext.Current.Request.Url.PathAndQuery, "") + HttpContext.Current.Request.ApplicationPath;
        if (!baseUrl.EndsWith("/"))
            baseUrl += "/";

        string notifyUrl = HttpUtility.UrlEncode(baseUrl + "Users/PayPal/Notify.aspx");
        string returnUrl = HttpUtility.UrlEncode(baseUrl + "Users/PayPal/OrderCompleted.aspx?ID=" + order.OrderId.ToString());
        string cancelUrl = HttpUtility.UrlEncode(baseUrl + "Users/PayPal/OrderCancelled.aspx");
        string business = HttpUtility.UrlEncode(Globals.Settings.Store.BusinessEmail);
        string itemName = HttpUtility.UrlEncode("Order #" + order.OrderId.ToString());

        StringBuilder url = new StringBuilder();
        url.AppendFormat(
           "{0}?cmd=_xclick&upload=1&rm=2&no_shipping=1&no_note=1&currency_code={1}&business={2}&item_number={3}&custom={3}&item_name={4}&amount={5}&notify_url={6}&return={7}&cancel_return={8}",
           serverUrl, Globals.Settings.Store.CurrencyCode, business, order.OrderId, itemName,
           amount, notifyUrl, returnUrl, cancelUrl);

        return url.ToString();
    }

    protected void lBtnClear_Click(object sender, EventArgs e)
    {
        Ample.Web.CurrentUserShoppingCart.Clear();
        panTotals.Visible = false;
        gvwOrderItems.DataBind();
    }
}
